1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*!
A converter for `isotope` ASTs into in-memory representation
*/
use crate::ast::{self, Expr, Scope, Statement};
use crate::error::*;
use crate::value::*;
use crate::*;
use hayami::{SymbolMap, SymbolTable};
use nom::{combinator::map_res, IResult};

/// A converter for `isotope` ASTs into in-memory representation
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Builder {
    symbols: SymbolTable<String, ValId>,
}

impl Builder {
    /// Create a new builder for `isotope` values
    #[inline]
    pub fn new() -> Builder {
        Builder::default()
    }
    /// Handle a statement
    pub fn statement(&mut self, statement: &Statement) -> Result<(), Error> {
        match statement {
            Statement::Instant(i) => self.instant(i)?,
            Statement::Param(p) => {
                self.param(p)?;
            }
            Statement::Let(l) => self.let_(l)?,
        }
        Ok(())
    }
    /// Construct a `ValId` value from an `Expr` AST
    pub fn expr(&mut self, expr: &Expr) -> Result<ValId, Error> {
        let result = match expr {
            // Basic expressions
            Expr::Ident(i) => self.ident(i)?,
            Expr::Sexpr(s) => self.sexpr(s)?,
            Expr::Lambda(l) => self.lambda(l)?.into_valid(),

            // Type theory
            Expr::Pi(p) => self.pi(p)?.into_valid(),
            Expr::Universe(level) => self.universe(*level)?,

            // Primitives
            Expr::Natural(n) => n.clone().into_valid(),
            Expr::Boolean(b) => b.into_valid(),
            Expr::Nat => Nat.into_valid(),
            Expr::Bool => Bool.into_valid(),

            // Lifetimes
            Expr::Lifetime(l) => self.lifetime(l)?,

            // Syntax sugar
            Expr::Scope(s) => self.scope(s)?,
            Expr::TypeOf(e) => self.expr(e)?.ty().clone(),
            _ => return Err(Error::Message("Not implemented: general Expr construction")),
        };
        Ok(result)
    }
    /// Construct a `ValId` from an ident
    pub fn ident(&self, ident: &str) -> Result<ValId, Error> {
        self.symbols
            .get(ident)
            .cloned()
            .ok_or(Error::UndefinedSymbol)
    }
    /// Get the symbol from an ident
    pub fn ident_symbol(&self, ident: &str) -> Result<SymbolId, Error> {
        match self
            .symbols
            .get(ident)
            .ok_or(Error::UndefinedSymbol)?
            .as_enum()
        {
            ValueEnum::Symbol(s) => Ok(s.id().clone()),
            _ => Err(Error::Message("Not a symbol")),
        }
    }
    /// Construct an S-expression
    pub fn sexpr(&mut self, sexpr: &ast::Sexpr) -> Result<ValId, Error> {
        self.sexpr_args(&sexpr.0[..])
    }
    /// Construct a lambda function
    pub fn lambda(&mut self, lambda: &ast::Lambda) -> Result<Lambda, Error> {
        // let max_fun_lin = lambda.max_fun_lin();
        let (symbol, result) = self.parametrized(&lambda.1)?;
        let lambda = Lambda::try_new(symbol, result)?;
        //TODO: fixme
        /*
        if lambda.fun_lin() <= max_fun_lin {
            Ok(lambda)
        } else {
            Err(Error::Message("Lambda linearity too strong!"))
        }
        */
        Ok(lambda)
    }
    /// Construct a pi type
    pub fn pi(&mut self, pi: &ast::Pi) -> Result<Pi, Error> {
        let fun_lin = pi.fun_lin();
        let (symbol, ty) = self.parametrized(&pi.1)?;
        let pi = Pi::try_new(symbol, ty, fun_lin)?;
        Ok(pi)
    }
    /// Construct a parametrized value
    pub fn parametrized(
        &mut self,
        parametrized: &ast::Parametrized,
    ) -> Result<(SymbolId, ValId), Error> {
        let (symbol, scope) = if parametrized.param.ty.is_some() {
            self.push();
            let symbol = self.param(&parametrized.param);
            (symbol, true)
        } else {
            let name = parametrized
                .param
                .name
                .as_deref()
                .ok_or(Error::Message("Unnamed, untyped parameter"))?;
            let symbol = self.ident_symbol(name);
            (symbol, false)
        };
        let pair =
            symbol.and_then(|symbol| self.expr(&parametrized.value).map(|value| (symbol, value)));
        if scope {
            self.pop()
        }
        pair
    }
    /// Construct an S-expression from an argument list
    pub fn sexpr_args(&mut self, mut args: &[Arc<Expr>]) -> Result<ValId, Error> {
        if args.is_empty() {
            return Ok(UNIT.clone());
        }
        let mut result = self.expr(&*args[0])?;
        args = &args[1..];
        while !args.is_empty() {
            let arg = self.expr(&*args[0])?;
            result = Sexpr::try_new(result, arg)?.into_valid();
            args = &args[1..];
        }
        Ok(result)
    }
    /// Construct a lifetime with a given constraint-set
    pub fn lifetime(&mut self, constraints: &Option<ast::Constraints>) -> Result<ValId, Error> {
        if let Some(constraints) = constraints {
            if !constraints.0.is_empty() {
                return self
                    .constraints(constraints)
                    .map(Lifetime::new)
                    .map(Value::into_valid);
            }
        }
        Ok(FREE_LIFETIME.clone())
    }
    /// Construct a judgement-set
    /// Construct a typing universe at a given level
    pub fn universe(&mut self, level: u64) -> Result<ValId, Error> {
        //TODO: better universes, lifetime quantification...
        Ok(Universe::new_free(level).into_valid())
    }
    /// Parse a scope
    pub fn scope(&mut self, scope: &Scope) -> Result<ValId, Error> {
        self.push();
        let mut errno = Ok(());
        for statement in scope.statements.iter() {
            match self.statement(statement) {
                Ok(_) => {}
                Err(err) => {
                    errno = Err(err);
                    break;
                }
            }
        }
        let result = match errno {
            Ok(()) => self.expr(&scope.result),
            Err(err) => Err(err),
        };
        self.pop();
        result
    }
    /// Push a new scope onto the symbol table
    pub fn push(&mut self) {
        self.symbols.push()
    }
    /// Pop a scope from the symbol table
    pub fn pop(&mut self) {
        self.symbols.pop()
    }
    /// Handle a free instant declaration
    pub fn instant(&mut self, instant: &ast::Instant) -> Result<(), Error> {
        let free_instant = self.free_instant(
            instant
                .constraint
                .as_ref()
                .unwrap_or(&ast::Constraints(vec![])),
        )?;
        if let Some(name) = instant.name.clone() {
            self.symbols.insert(name, free_instant.into_valid())
        }
        Ok(())
    }
    /// Handle a parameter declaration, returning the new parameter
    pub fn param(&mut self, param: &ast::Param) -> Result<SymbolId, Error> {
        match (&param.name, &param.ty) {
            (name, Some(ty)) => {
                let ty = self.expr(ty)?;
                let param = SymbolId::param(ty)?;
                if let Some(name) = name {
                    self.symbols
                        .insert(name.clone(), param.clone().into_valid());
                }
                Ok(param)
            }
            _ => Err(Error::Message("Invalid parameter declaration")),
        }
    }
    /// Handle a let statement
    pub fn let_(&mut self, let_: &ast::Let) -> Result<(), Error> {
        let value = self.expr(&let_.value)?;
        if let Some(judgement) = &let_.judgement {
            //TODO: check judgement
            unimplemented!("Checking judgement {:?}", judgement)
        }
        self.symbols.insert(let_.name.clone(), value);
        Ok(())
    }
    /// Construct a free instant having a given constraint-set
    pub fn free_instant(&mut self, _constraints: &ast::Constraints) -> Result<SymbolId, Error> {
        unimplemented!()
    }
    /// Construct an individual constraint-set
    pub fn constraints(&mut self, constraints: &ast::Constraints) -> Result<Constraint, Error> {
        let mut set = Constraint::new();
        for constraint in constraints.0.iter() {
            let (instant, relationship) = self.constraint(constraint)?;
            set.require(Some(instant), relationship, true)?;
        }
        Ok(set)
    }
    /// Construct an individual constraint
    pub fn constraint(
        &mut self,
        constraint: &ast::Constraint,
    ) -> Result<(ValId, Relationship), Error> {
        let value = self.ident(&constraint.1)?;
        Ok((value, constraint.0))
    }
    /// Parse an expression, yielding a `ValId`
    pub fn parse_expr<'a>(&mut self, input: &'a str) -> IResult<&'a str, ValId> {
        map_res(crate::parser::expr, |expr| self.expr(&expr))(input)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::*;

    #[test]
    fn basic_exprs_build() {
        let exprs = [
            "#lambda x: #bool => x",
            "#lambda x: #bool => #true",
            "#lambda x: #bool => #false",
            "#lambda x: #nat => 34",
            "#fn T: #universe[0] => T",
            "#fn _: #bool => #bool",
            "#lambda x: #bool => #lambda y: #bool => x",
            "#lambda T: #universe[0] => #lambda x: T => #lambda y: T => x",
            "#fn T: #universe[0] => #fn _: T => #fn _: T => T",
        ];
        let mut builder = Builder::new();
        for &input in &exprs {
            let (rest, expr) = expr(input).expect(input);
            assert_eq!(rest, "");
            builder.expr(&expr).expect(input);
        }
    }

    #[test]
    fn basic_exprs_build_properly() {
        let pairs = [
            ("#true", true.into_valid()),
            ("#false", false.into_valid()),
            ("#bool", Bool.into_valid()),
            ("#nat", Nat.into_valid()),
            ("#universe[0]", PROP.clone()),
            ("#universe[1]", SET.clone()),
            ("#universe[2]", TYPE.clone()),
            (
                "#lambda x: #bool => #true",
                Lambda::try_new(
                    SymbolId::param(Bool.into_valid()).unwrap(),
                    true.into_valid(),
                )
                .unwrap()
                .into_valid(),
            ),
        ];
        let mut builder = Builder::new();
        for (input, output) in pairs.iter() {
            let (rest, expr) = expr(input).expect(input);
            assert_eq!(rest, "");
            let value = builder.expr(&expr).expect(input);
            assert_eq!(value, *output);
        }
    }

    #[test]
    fn higher_order_function() {
        let program = [
            "#let unary = #fncopy _: #bool => #bool;",
            "#let eval_true = #lambda f: unary => (f #true);",
            "#let id = #lambda x: #bool => x;",
            "#let id_true = (eval_true id);",
        ];
        let mut builder = Builder::new();
        for stmt in program.iter() {
            let (rest, parse) = statement(stmt).expect(stmt);
            assert_eq!(rest, "");
            builder.statement(&parse).expect(stmt);
        }
        assert_eq!(
            builder.ident("id_true").unwrap().normalized().unwrap(),
            &*crate::value::TRUE
        );
    }
}